package com.itboye.eweilisten.me.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.eweilisten.R;
import com.itboye.eweilisten.adapter.GoodsAdapter;
import com.itboye.eweilisten.app.MyApplication;
import com.itboye.eweilisten.base.MaBaseActivity;
import com.itboye.eweilisten.me.home.fragment.FragmentGoods;
import com.itboye.eweilisten.me.login.LoginActivity;
import com.itboye.eweilisten.model.GoodsDetailBean;
import com.itboye.eweilisten.presenter.UserPresenter;
import com.itboye.eweilisten.util.sputil.Const;
import com.itboye.eweilisten.util.sputil.SPUtils;
import com.itboye.eweilisten.util.widget.CarouselView;
import com.itboye.eweilisten.util.widget.ExperienceDialog;
import com.itboye.eweilisten.util.widget.IsStringSPUtils;
import com.itboye.eweilisten.util.widget.MyListView;
import com.itboye.eweilisten.util.widget.StickyScrollView;
import com.itboye.eweilisten.util.widget.XImageLoader;
import com.itboye.eweilisten.volley.ResultEntity;
import com.jaeger.library.StatusBarUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 商品详情
 */
public class ActivityGoodsTetail extends MaBaseActivity implements View.OnClickListener, Observer {
//    private TextView tvNoPrice;//价格
    TextView oneTextView;
    private StickyScrollView scrollView;
    private int height;
    private LinearLayout llContent;
    private RelativeLayout llTitle;
    private FrameLayout frameLayout;
    private TextView title1;
    private CarouselView cCarouselView;
    private TextView tvBuyNow;
    private boolean ischat;
    private TextView tvexperience;//立即体验
    private TextView tvGoodsPrice;//价格
    UserPresenter presenter;
    GoodsDetailBean bean = new GoodsDetailBean();
    private String id;//商品ID
    private TextView tvGoodsName;//商品标题
    private TextView tvGoodsSecondary_headlines;//描述
    private MyListView goodsListview;
    GoodsAdapter adapter;
    String value_id;
    private int post;
    private int i;
    private ImageView back;
//    private TextView back;
    private List<ImageView> bmps;
    private ImageView tvBack;

    String uid;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        //去除title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
//去掉Activity上面的状态栏
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN, WindowManager.LayoutParams. FLAG_FULLSCREEN);

        setContentView(R.layout.activity_goods_detail);
        initView();
        initListeners();
        uid = (String) SPUtils.get(MyApplication.instance, null, Const.ID, "");
        id = getIntent().getStringExtra("id");
        presenter = new UserPresenter(this);
        showProgressDialog("数据加载中...", true);
        presenter.onGoodsInfo(id,uid, IsStringSPUtils.getSid());

        //登录的广播
        IntentFilter filter = new IntentFilter(LoginActivity.LOGIN);
        registerReceiver(loginReceiver, filter);
        //网络广播
        IntentFilter connect_recover = new IntentFilter("connect_recover");
        registerReceiver(netBroadcastReceiver,connect_recover);
    }

    BroadcastReceiver loginReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            uid = (String) SPUtils.get(MyApplication.instance, null, Const.ID, "");
        }


    };
    /**
     * 获取网络回复的广播
     *
     * @return
     */

    BroadcastReceiver netBroadcastReceiver= new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("connect_recover")&&intent.getIntExtra("recover",0)==400){
                presenter.onGoodsInfo(id,uid,IsStringSPUtils.getSid());

            }
        }
    };
    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(loginReceiver);
//        unregisterReceiver(netBroadcastReceiver);
    }

    /**
     * 初始化View
     */
    private void initView() {
        scrollView = (StickyScrollView) findViewById(R.id.scrollView);
        frameLayout = (FrameLayout) findViewById(R.id.tabMainContainer);
        title1 = (TextView) findViewById(R.id.title);
        oneTextView = (TextView) findViewById(R.id.infoText);
        llContent = (LinearLayout) findViewById(R.id.ll_content);
        llTitle = (RelativeLayout) findViewById(R.id.ll_good_detail);
        oneTextView.setOnClickListener(this);

//        scrollView.setOnScrollListener(this);
        StatusBarUtil.setTranslucentForImageView(ActivityGoodsTetail.this, 0, title1);
//        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) llTitle.getLayoutParams();
//        params.setMargins(0, getStatusHeight(), 0, 0);
//        llTitle.setLayoutParams(params);

        //默认设置一个Frg
        getSupportFragmentManager().beginTransaction().replace(R.id.tabMainContainer, FragmentGoods.newInstance()).commit();
    }

    ExperienceDialog experienceDialog;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                this.finish();
                break;
            case R.id.infoText:
                getSupportFragmentManager().beginTransaction().replace(R.id.tabMainContainer, FragmentGoods.newInstance()).commit();
                break;
            case R.id.tvBuyNow:
                if (uid == null || uid.equals("")) {//uid为空的时候跳转到登陆
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                if (experienceDialog == null)
                    Log.d("experienceDialog", value_id + "\t" + post);
                experienceDialog = new ExperienceDialog(this,bean, false, id, post);
                experienceDialog.show(getSupportFragmentManager(), "");
                break;
            case R.id.tvexperience:
//                if (value_id == null || value_id.equals("")) {
//                    MAlert.alert("请选择");
//                    return;
//                }
                Intent intent = new Intent(this, ActivityExperience.class);
                intent.putExtra("countment", bean.getSecondary_headlines());
                intent.putExtra("name", bean.getName());
                intent.putExtra("imgid", bean.getMain_img());
                intent.putExtra("id", bean.getId());
                //是否过期参数：bought
                if(!(bean.getExpire_time()==null||"".equals(bean.getExpire_time()))){
                    if((Long.valueOf(bean.getExpire_time())- (System.currentTimeMillis()/1000)) <= 0){
                        intent.putExtra("bought",false);
                    }else {
                        intent.putExtra("bought",true);
                    }
                }
                startActivity(intent);

                break;
            case R.id.tvBack:
                finish();
                break;
        }

    }

    @Override
    public void update(Observable o, Object arg) {
        ResultEntity entity = handlerError(arg);
        if (entity != null) {
            if (entity.getCode().equals("1111")) {
                Intent intent = new Intent(MyApplication.instance, LoginActivity.class);
                startActivity(intent);
                return;
            }
            if (entity.getEventType() == presenter.Goods_success) {
                bean = (GoodsDetailBean) entity.getData();
                onUpdate(bean);
                adapter = new GoodsAdapter(this, bean);
                goodsListview.setAdapter(adapter);
                goodsListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        value_id = bean.getSku_list().get(position).getSku_desc();
                        post = position;
                        adapter.notifyDataSetChanged();
                        adapter.setChecked(position);//传入现在选择的position

                        DecimalFormat df = new DecimalFormat("######0.00");
                        double d1 = Double.parseDouble(bean.getSku_list().get(position).getPrice());
                        String Orprice = df.format(d1 / 100);
                        tvGoodsPrice.setText("¥" + Orprice + "");
                    }
                });
            }

        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }

    /***
     * 赋值
     * @param bean
     */
    public void onUpdate(GoodsDetailBean bean) {
        for (i = 0; i < bean.getSku_list().size(); i++) {
            DecimalFormat df = new DecimalFormat("######0.00");
            double d1 = Double.parseDouble(bean.getSku_list().get(0).getPrice());
            String Orprice = df.format(d1 / 100);
            tvGoodsPrice.setText("¥" + Orprice + "");
//            tvNoPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中间横线

            double price = Double.parseDouble(bean.getSku_list().get(i).getOri_price());
            String toProce = df.format(price / 100);
//            tvNoPrice.setText(toProce + "");
        }
        tvGoodsSecondary_headlines.setText(bean.getSynopsis());
        tvGoodsName.setText(bean.getName());
        if (bean.getCarousel_images()!=null&&bean.getCarousel_images().size()>0){
            bmps = new ArrayList<ImageView>();
            Log.d("imageView", bean.getCarousel_images().get(0) + "");
            for (int k = 0; k < bean.getCarousel_images().size(); k++) {
                ImageView imageView = new ImageView(this);
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                XImageLoader.load(Const.IMAGE_HEAD
                        + bean.getCarousel_images().get(k), imageView);
                bmps.add(imageView);
                Log.d("imageView", bean.getCarousel_images().get(k) + "");
            }
            cCarouselView.setImageBitmaps(bmps);
        }else{
            cCarouselView.setBackgroundResource(R.drawable.logo_one);
        }

    }

    private void initListeners() {
        //获取内容总高度
        final ViewTreeObserver vto = llContent.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                height = llContent.getHeight();
                //注意要移除
                llContent.getViewTreeObserver()
                        .removeGlobalOnLayoutListener(this);

            }
        });

        //获取Fragment高度
        ViewTreeObserver viewTreeObserver = frameLayout.getViewTreeObserver();
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                height = height - frameLayout.getHeight();
                //注意要移除
                frameLayout.getViewTreeObserver()
                        .removeGlobalOnLayoutListener(this);
            }
        });

        //获取title高度
        ViewTreeObserver viewTreeObserver1 = llTitle.getViewTreeObserver();
        viewTreeObserver1.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                height = height - llTitle.getHeight() - getStatusHeight();//计算滑动的总距离
                scrollView.setStickTop(llTitle.getHeight() + getStatusHeight());//设置距离多少悬浮
                //注意要移除
                llTitle.getViewTreeObserver()
                        .removeGlobalOnLayoutListener(this);
            }
        });
    }

  /*  @Override
    public void onScrollChanged(int l, int t, int oldl, int oldt) {
        if (t <= 0) {
            llTitle.setBackgroundColor(Color.argb((int) 0, 255, 255, 255));
            StatusBarUtil.setTranslucentForImageView(ActivityGoodsTetail.this, 0, title1);
        } else if (t > 0 && t <= height) {
            float scale = (float) t / height;
            int alpha = (int) (255 * scale);
//            llTitle.setBackgroundColor(Color.argb((int) alpha, 227, 29, 26));//设置标题栏的透明度及颜色
            StatusBarUtil.setTranslucentForImageView(ActivityGoodsTetail.this, alpha, title1);//设置状态栏的透明度
        } else {
//            llTitle.setBackgroundColor(Color.argb((int) 255, 227, 29, 26));
            StatusBarUtil.setTranslucentForImageView(ActivityGoodsTetail.this, 255, title1);
        }
    }*/

    /**
     * 获取状态栏高度
     *
     * @return
     */
    private int getStatusHeight() {
        int resourceId = ActivityGoodsTetail.this.getResources().getIdentifier("status_bar_height", "dimen", "android");
        return getResources().getDimensionPixelSize(resourceId);

    }

}
